package com.itao.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @Author sjt
 * @CreateTime 2023/10/15 14:31
 */
public class JdomTest {

    public static void main(String[] args)  throws Exception {
        //read();
        write();
    }

    private static void read() throws Exception {
        var saxBuilder = new SAXBuilder();
        var document = saxBuilder.build(new File("E:\\idea\\java-learn\\xml\\src\\main\\resources\\read.xml"));
        // 获取根元素
        var rootElement = document.getRootElement();
        System.out.println("rootElement: " + rootElement.getName());
        // 获取元素
        var children = rootElement.getChildren();
        children.forEach(e -> {
            System.out.println(e.getName());
            System.out.println(e.getAttribute("no").getValue());
        });
    }

    private static void write() throws Exception {
        var document = new Document();
        var school = new Element("school");

        var aClass = new Element("class");
        aClass.setAttribute("no", "1801");

        var student = new Element("student");
        student.setAttribute("no", "1");

        var name = new Element("name");
        name.setText("张鹏飞");
        var sex = new Element("sex");
        sex.setText("男");
        var addr = new Element("addr");
        addr.setText("武汉");

        document.setRootElement(school);
        school.addContent(aClass);
        aClass.addContent(student);
        student.addContent(name);
        student.addContent(sex);
        student.addContent(addr);

        XMLOutputter xmlOutputter = new XMLOutputter();
        xmlOutputter.setFormat(Format.getPrettyFormat());
        try (var os = new FileOutputStream("E:\\idea\\java-learn\\xml\\src\\main\\resources\\jdom-write.xml")){
            xmlOutputter.output(document, os);
        }

    }
}
